use lazy_static::lazy_static;
use plc::{do_cmd, SvCache};
use std::time::Duration;
use tracing::{instrument, warn};
use tracing_subscriber::prelude::*;
use warp::{hyper::body::Bytes, Filter};

#[instrument(skip_all, name = "main")]
#[tokio::main]
async fn main() {
    base::trace_warn!();

    lazy_static! {
        static ref CACHE: SvCache = SvCache::builder()
            .max_capacity(9_0000)
            .time_to_idle(Duration::from_secs(24 * 60 * 60)) // 1 days
            .build();
    }

    let md = "plc";
    let body = base::body!();

    let post_two = warp::path(md)
        .and(warp::path::param())
        .and(body)
        .and_then(move |cmd: String, data: Bytes| async { do_cmd(data, cmd, CACHE.clone()).await });

    let post = warp::post().and(post_two).with(base::cors!());

    let get = warp::get().map(move || format!("\nserve: {}\n\n", md));
    let opt = base::opt!();

    let route = get.or(opt).or(post);

    warn!("listening on 0.0.0.0:9985");

    warp::serve(route).run(([0, 0, 0, 0], 9985)).await;
}
